package com.showcal.send;

import com.showcal.send.ConstantData;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 短信处理类
 * @author  Kevin Li
 * @date 2015年6月5日 下午5:29:19
 * @Title: MsgUtil
 * @ClassName: MsgUtil
 * @Description:
 */
public class ShowcalMsgUtil {

	private static String MSG_SERVER_URL = "http://sms.api.ums86.com:8899/sms/Api/Send.do?"; //短信发送地址
	private static String MSG_SERVER_BALANCE = "http://sms.api.ums86.com:8899/sms/Api/SearchNumber.do?"; //查询剩余短信地址

	private static String MSG_SERVER_SPCODE = "226480"; //企业 编号
	private static String MSG_SERVER_LOGINNAME = "SKWR"; //短信账户
	private static String MSG_SERVER_PASSWORD = "Showcal2015jc"; //密码
	//发送短信
	private static String MSG_METH_SENDMSG = MSG_SERVER_URL + "SpCode=" + MSG_SERVER_SPCODE + "&LoginName=" + MSG_SERVER_LOGINNAME + "&Password=" + MSG_SERVER_PASSWORD;
	//查询剩余短信
	private static String MSG_METH_GETBALANCE = MSG_SERVER_BALANCE + "SpCode=" + MSG_SERVER_SPCODE + "&LoginName=" + MSG_SERVER_LOGINNAME + "&Password=" + MSG_SERVER_PASSWORD;
	private static ShowcalMsgUtil smsTool;
	private static Map<String, String> errorMsg = new ConcurrentHashMap<>();
	static {
		errorMsg.put("0", "发送短信成功");
		errorMsg.put("1", "提交参数不能为空");
		errorMsg.put("2", "账号无效或权限不足");
		errorMsg.put("3", "账号密码错误");
		errorMsg.put("4", "预约发送时间格式不正确，应为yyyyMMddHHmmss");
		errorMsg.put("5", "IP不合法");
		errorMsg.put("6", "号码中含有无效号码或不在规定的号段或为免打扰号码（包含系统黑名单号码）");
		errorMsg.put("7", "非法关键字");
		errorMsg.put("8", "内容长度超过上限，最大402字或字符");
		errorMsg.put("9", "接受号码过多，最大1000");
		errorMsg.put("11", "提交速度太快");
		errorMsg.put("12", "您尚未订购[普通短信业务]，暂不能发送该类信息");
		errorMsg.put("13", "您的[普通短信业务]剩余数量发送不足，暂不能发送该类信息");
		errorMsg.put("14", "流水号格式不正确");
		errorMsg.put("15", "流水号重复");
		errorMsg.put("16", "超出发送上限（操作员帐户当日发送上限）");
		errorMsg.put("17", "余额不足");
		errorMsg.put("18", "扣费不成功");
		errorMsg.put("20", "系统错误");
		errorMsg.put("21", "密码错误次数达到5次");
		errorMsg.put("24", "帐户状态不正常");
		errorMsg.put("25", "账户权限不足");
		errorMsg.put("26", "需要人工审核");
		errorMsg.put("28", "发送内容与模板不符");
		errorMsg.put("29", "扩展号太长或不是数字&accnum=");
		errorMsg.put("32", "同一号码相同内容发送次数太多（默认24小时内，验证码类发送5次或相同内容3次以上会报此错误。）");
	}

	public static ShowcalMsgUtil getInstance() {
		if (smsTool == null) {
			try {

				smsTool = new ShowcalMsgUtil();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return smsTool;
	}



    /**
     * @author  Kevin
     * @param mobile
     * @param message
     * @return
     */
	public  String sendMsg(String mobile, String message) {
		String result = "";
		try {

			StringBuffer sb = new StringBuffer(MSG_METH_SENDMSG);

			sb.append("&MessageContent=" + URLEncoder.encode(message, "GBK")); //短信内容
			sb.append("&UserNumber=" + mobile); //手机号码
			sb.append("&SerialNumber=" + randomDigital()); //流水号，20位数字
			//sb.append("&ScheduleTime=" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())); //预约发送时间，格式:yyyyMMddHHmmss,如‘20090901010101’，立即发送请填空
			sb.append("&f=" + "1"); //拼接短信内容
			URL url = new URL(sb.toString());
			HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
			hConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			hConn.setRequestMethod("POST");
			System.out.println("url：" + url);
			BufferedReader bfrd = new BufferedReader(new InputStreamReader(url.openStream()));
			//返回发送结果
			String inputline = bfrd.readLine();
			System.out.println(inputline);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取短信余额
	 * @author  Kevin Li
	 * @date 2015年6月5日 下午1:06:16
	 * @Title getMsgBalance
	 * @Description 
	 * @return
	 * @throws Exception String 
	 * @throws
	 */
	public static String getMsgBalance() {
		String result = "0";
		try {
			StringBuffer sb = new StringBuffer(MSG_METH_GETBALANCE);
			URL url = new URL(sb.toString());
			HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
			hConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			hConn.setRequestMethod("POST");
			System.out.println("url：" + url);
			BufferedReader bfrd = new BufferedReader(new InputStreamReader(url.openStream()));
			// 返回发送结果
			String inputline = bfrd.readLine();

			// 返回结果为大于0 发送成功
			if (inputline != null && !"".equals(inputline)) {
				System.out.println(inputline);
			}
		} catch (Exception e) {

			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取错误信息
	 * @param code
	 * @return
	 */
	public static String getErrorMsg(String code) {
		if (errorMsg.containsKey(code)) {
			return errorMsg.get(code);
		} else {
			return "未知错误";
		}
	}

	public static String randomDigital() {

		String str = "";
		str += (int) (Math.random() * 9 + 1);

		for (int i = 0; i < 19; i++) {//
			str += (int) (Math.random() * 10);

		}

		return str;
	}

	public static void main(String[] args) {
		try {
			String mobile = "18790506617";
			String message = ConstantData.SC_SHORT_MESSAGE_PRE;

			System.out.println(ShowcalMsgUtil.getInstance().sendMsg(mobile, ConstantData.SC_SHORT_MESSAGE_PRE + 7777));
			//System.out.println(getMsgBalance());
			//final DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
			//System.out.println(dateFormat.getInstance().toString());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
